<template>
  <el-dialog v-model="dialogVisible" title="角色权限管理" width="70%" top="5vh">
    <el-tabs v-model="activeTab">
      <el-tab-pane v-for="role in roles" :key="role.id" :label="role.name" :name="role.id.toString()">
        <el-card class="box-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>{{ role.name }} 拥有的权限</span>
              <el-dropdown trigger="click">
                <el-button type="primary">
                  新增权限 <i class="bi bi-plus-lg ms-1"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item 
                      v-for="perm in remainingPermissions(role.id)" 
                      @click="handleAssignPermission(role.id, perm)"
                      :key="perm">
                      {{ perm }}
                    </el-dropdown-item>
                    <el-dropdown-item v-if="remainingPermissions(role.id).size === 0" disabled>
                      已拥有全部权限
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          
          <div v-if="currentPermissions(role.id).size > 0" class="permission-group">
            <el-tag v-for="perm in currentPermissions(role.id)" :key="perm" class="permission-tag">
              {{ perm }}
            </el-tag>
          </div>
          <el-empty v-else description="该角色无任何权限"></el-empty>

        </el-card>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import { usePermissionService } from '@/stores/permissionService';
import { ElMessageBox, ElMessage } from 'element-plus'; // 新增
const permissionService = usePermissionService();

const dialogVisible = ref(false);
const activeTab = ref('1'); // 默认显示管理员
const roles = ref([
  { id: 1, name: '系统管理员' },
  { id: 2, name: '培训导师' },
  { id: 3, name: '护理学员' }
]);

// --- 计算属性 ---
const currentPermissions = (roleId) => {
  return permissionService.getPermissionsByRoleId(roleId);
};

const remainingPermissions = (roleId) => {
  const allPerms = permissionService.allPermissions;
  const currentPerms = currentPermissions(roleId);
  return new Set([...allPerms].filter(p => !currentPerms.has(p)));
};

// --- 方法 ---
const open = () => {
  dialogVisible.value = true;
};
/**
 * 新增：处理分配权限的逻辑
 * @param {number} roleId - 目标角色ID
 * @param {string} permission - 要分配的权限描述
 */
 const handleAssignPermission = async (roleId, permission) => {
  try {
    // 1. 弹出确认框
    await ElMessageBox.confirm(
      `确定要为角色【${roles.value.find(r => r.id === roleId)?.name}】添加权限【${permission}】吗？此操作不可撤销`,
      '权限分配确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 2. 用户点击确认后，调用接口
    await permissionService.assignPermissionToRole(roleId, permission);

    // 3. 成功后给出提示
    ElMessage.success('权限分配成功！');

    // 4. 刷新缓存，UI将自动更新
    //    这里我们直接调用 cacheAllRolePermissions，它会从后端获取最新的权限数据
    await permissionService.cacheAllRolePermissions();

  } catch (error) {
    // 如果用户点击了“取消”，或者接口调用失败
    if (error !== 'cancel') {
      ElMessage.error('权限分配失败: ' + error);
    } else {
      ElMessage.info('已取消操作');
    }
  }
};
// 暴露 open 方法给父组件
defineExpose({
  open
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}
.permission-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  max-height: 50vh; /* 限制权限列表的最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
.permission-tag {
  font-size: 14px;
}
.ms-1 {
  margin-left: 0.25rem;
}
</style>